<template>
   <el-container class="home-container">
     <!-- 修改密码 -->
     <el-dialog title="修改密码"  :visible.sync="passDialogFormVisible">
        <el-form :model="passForm" :rules="passRules" ref="passForm" label-width="100px" class="demo-ruleForm">
           <el-form-item label="旧密码" prop="password">
                <el-input type="password" v-model="passForm.password" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newpassword1">
                <el-input type="password" v-model="passForm.newpassword1" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newpassword2">
                <el-input type="password" v-model="passForm.newpassword2" style="width:300px;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="passDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="updatePass('passForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 个人资料 -->
     <el-dialog title="个人资料" :visible.sync="myDialogFormVisible">
        <el-form :model="updateForm" :rules="rules" ref="updateForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="头像" prop="name">
                <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/api/file/fileUpload"
                :headers="headers"
                name="file"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="updateForm.username" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="updateForm.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="身份证号码" prop="idCard">
                <el-input v-model="updateForm.idCard" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="电话号码" prop="phone">
                <el-input v-model="updateForm.phone" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="家庭住址">
                <el-input v-model="updateForm.address" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="updateForm.email" style="width:300px;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="myDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSaveForm('updateForm')">确 定</el-button>
        </div>
      </el-dialog>
       <!-- 头部区域 -->
       <el-header style="height:50px">
           <div>
               <img src="../assets/img/iot.png" style="width:30px;height:30px;padding:10px" alt="">
               <span>物联网管理系统</span>
           </div>
           <div>
             <!-- 通知 -->
               <!-- <div class="notice">
                 <el-badge value="12" class="item" >
                  <span class="el-icon-bell"></span>
                </el-badge>
               </div> -->
               <!--我的 -->
               <div class="person">
                 <el-dropdown trigger="click">
                  <span class="el-dropdown-link">
                    <div style="padding: 0 12;">
                      <!-- 头像 -->
                      <el-avatar v-if="currentUser.avatar != null"  :src="'http://localhost:8888/file/getImgById?id='+ currentUser.avatar"></el-avatar>
                      <el-avatar v-else  icon="el-icon-user-solid"></el-avatar>
                    </div>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="myDialogFormVisible = true">个人资料</el-dropdown-item>
                    <el-dropdown-item @click.native="passDialogFormVisible = true">修改密码</el-dropdown-item>
                    <el-dropdown-item @click.native="logout()">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
               </div>
           </div>
       </el-header>
        <el-container>
            <!-- 侧边栏 -->
            <el-aside :width="isCollapse? '60px':'200px'">
              <div class="toggle-button" @click="toggleCollapse()">
                <i :class="isCollapse?'el-icon-s-unfold':'el-icon-s-fold'"></i>
              </div>
                <el-menu    
                    class="el-menu-vertical-demo"
                    background-color="#313743"
                    active-text-color="#409eff"
                    text-color="#fff"
                    unique-opened
                    :collapse="isCollapse"
                    :collapse-transition="false"
                    router
                    >
                    <el-menu-item index="/main/Home">
                      <i class="el-icon-s-home"></i>
                      <span slot="title">首页</span>
                    </el-menu-item>
                    <el-submenu :index="item.id + ''" v-for="item in menuList" :key="item.id">
                        <template slot="title">
                            <i :class="item.icon"></i>
                            <span>{{item.name}}</span>
                        </template>
                        <el-menu-item :index="'/main'+childItem.componentPath + ''" v-for="childItem in item.childrenMenus" :key="childItem.id">
                          <template slot="title">
                            <i :class="childItem.icon"></i>
                            <span>{{childItem.name}}</span>
                         </template>
                        </el-menu-item>
                    </el-submenu>
                </el-menu>
            </el-aside>
            <!-- 右侧主体 -->
            <el-main>
                <router-view></router-view>
            </el-main>
        </el-container>
   </el-container>
</template>

<script>
import Qs from 'qs';
export default {
  data() {
    return {
      currentUser:{},
      imageUrl:"",
      headers:{
        token: window.sessionStorage.getItem('token')
      },
      myDialogFormVisible:false,//个人资料是否显示
      passDialogFormVisible: false,//修改密码是否显示
      formLabelWidth: '80px',
      passForm:{//修改密码
        password:"",//原密码
        newpassword1:"",//新密码
        newpassword2:""//新密码
      },
      updateForm:{
        },
      isCollapse: false,//侧边菜单是否折叠
      menuList:[],// 菜单列表
      active:'',
      rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ],
          idCard: [
            { required: true, message: '请填写身份证号码', trigger: 'blur'}
          ],
          phone: [
            { required: true, message: '请填写电话号码', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请填写邮箱地址', trigger: 'blur' }
          ]
      },
      passRules: {
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
          ],
          newpassword1: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
          ],
          newpassword2: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
          ],
      }
    };
  },
  watch: {
  },
  created: function() {
    // 初始化时获取菜单列表
    this.getUserById();
    this.getMenuList();
  },

  computed: {
    config: function() {
      return this.$store.state.configOptions.config;
    }
  },
  methods: {
    //获取当前用户信息
     async getUserById(){
      const res =await this.$http.get("/user/getUserById")
      if(res.data.code === 200){
        console.log(res);
        this.currentUser = res.data.data;
        this.updateForm = res.data.data;
      }else{
        this.$message.error("获取当前用户信息失败");
      }
    },
    //修改我的资料
    submitSaveForm(formName){
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const res = await this.$http.post("/user/updateUser",Qs.stringify(this.updateForm))
            if(res.data.code === 200){
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
              // 隐藏面板
              this.myDialogFormVisible = false;
            }else{
              this.$message.error(res.data.msg);
            }
          } else {
            return false;
          }
        });
    },
    // 路由跳转
    to(path){
      this.$router.push(path);
    },
    // 侧边菜单折叠
    toggleCollapse(){
      this.isCollapse = !this.isCollapse;
    },
    // 获取菜单列表
    async getMenuList(){
       const res =await this.$http.get("/menu/getMenus")
      if(res.data.code === 200){
        this.menuList = res.data.data;
      }else{
        this.$message.error("获取菜单失败");
         this.$router.replace('/login');
      }
    },
    //修改密码
    async updatePass(formName){
      this.$refs[formName].validate(async (valid) => {
        console.log(formName, valid)
          if (valid) {
            const res = await this.$http.post("/user/updatePass",Qs.stringify(this.passForm))
            if(res.data.code === 200){
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
              this.passDialogFormVisible = false
              this.logout();
            }else{
              this.$message.error(res.data.msg);
            }
          } else {
            return false;
          }
        });
    },
    //退出登录
    async logout(){
      const res =await this.$http.post("user/logout",this.form);
      console.log(res);
      if(res.data.code != 200){
        this.$message.error("退出登录失败");
      }else{
        this.$message({
          message: '您已退出登录成功',
          type: 'success'
        });
        window.sessionStorage.removeItem("token");
        this.$router.replace('/login');
      }
    },
     // 处理头像提交成功事件
    handleAvatarSuccess(res, file) {
      if(res.code === 200){
         this.$message({
          message: res.msg,
          type: 'success'
        });
        this.updateForm.avatar = res.data;
        this.imageUrl = URL.createObjectURL(file.raw);
      }else{
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        });
      }
       
    },
    //文件上传前处理
    beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isJPG) {
        //     this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        // return isJPG && isLt2M;
        return isLt2M;
    }
  }
}
</script>

<style>
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 200px;
    min-height: 400px;
  }
  .el-header{
      display: flex;
      padding-left: 0;
      justify-content: space-between;
      align-items: center;
      background-color: #373d41;
      color: white;
      font-size: 20px;
      
  }
  .el-header div{
      display: flex;
      align-items: center;
  }
  .el-aside{
      background-color: #313743;
  }
  .el-menu{
    border-right:none;
  }
  .el-main{
      background-color: #eaedfe;
      width: 100%;
  }
  .home-container{
      height: 100%;
  }


  /* 通知 */
  .notice{
    margin-right: 50px;
    border-radius: 5px;
    text-align: center;
    
  }


  /* 左边侧边栏 */
  .toggle-button{
    background-color: #4A5064;
    font-size: 20px;
    line-height: 40px;
    color: #fff;
    text-align: center;
    letter-spacing: 0.2em;
    cursor: pointer;
    
  }
  .el-container .el-main{
    padding-bottom: 0;
    padding-right: 0;
  }

  /* 头像上传 */
.el-upload {
    border: 1px dashed #750e0e;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
.el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 130px;
    height: 130px;
    line-height: 130px;
    text-align: center;
  }
  .avatar {
    width: 100%;
    height: 100%;
    display: block;
  }
  .avatar-uploader{
    width: 130px;
    height: 130px;
    border: 1px solid #b2b8c0;
    margin-left: 50px;
  }

</style>